# -*- coding: utf-8 -*-
import html
import os

from docxtpl import DocxTemplate
import openpyxl


class InfoForm:
    def __init__(self, name, sex, major, cls, stuNo, pointsSum, courseCount):
        self.name = name
        self.sex = sex
        self.major = major
        self.cls = cls
        self.stuNo = stuNo
        self.pointsSum = pointsSum
        self.courseCount = courseCount


def generate(infoForm):
    path = '模板/毕业学分预警告知书.docx'
    tpl = DocxTemplate(path)
    context = {
        'name': infoForm.name,  # 姓名
        'sex': infoForm.sex,  # 性别
        'major': infoForm.major,
        'cls': infoForm.cls,  # 班级
        'stuNo': infoForm.stuNo,
        'pointsSum': infoForm.pointsSum,
        'courseCount': infoForm.courseCount

    }
    tpl.render(context)
    directory = '/Users/lidaoyu/Downloads/毕业学分预警/'  # 存储文件夹
    if not os.path.exists(directory):  # 若文件夹不存在则先创建文件夹
        os.makedirs(directory)
        print(f"文件夹 '{directory}' 创建成功!")
    word_file = f'{infoForm.stuNo}{infoForm.name}毕业学分预警告知书.docx'  # 命名文件"文书号姓名处分类型.docx"
    tpl.save(f'{directory}{word_file}')  # 存储文件


def readExcel(path):
    workbook = openpyxl.load_workbook(path)  # 打开 Excel 文件
    sheet = workbook.active  # 选择第一个工作表

    # 获取行数和列数
    rows = sheet.max_row
    cols = sheet.max_column

    # 获取标题行的数据
    headers = []
    for col in range(1, cols + 1):
        header = sheet.cell(row=1, column=col).value
        headers.append(header)

    # 逐行读取数据并以字典形式存储
    for row in range(2, rows + 1):
        row_data = {}  # 创建一个空字典用于存储每一行的数据

        # 逐列读取数据
        for col in range(1, cols + 1):
            header = headers[col - 1]  # 获取标题
            cell_value = sheet.cell(row=row, column=col).value  # 获取单元格的值
            # cell_value = html.escape(cell_value)  # 替换特殊符号(<,>,&)
            row_data[header] = cell_value  # 将值添加到字典中

        info = InfoForm(**row_data)  # 根据行信息调用构造函数
        generate(info)  # 根据信息调用生成函数

    workbook.close()  # 关闭 Excel 文件


if __name__ == '__main__':
    readExcel('数据/毕业学分预警数据.xlsx')  # 读取数据
    print('文件已生成!')
